<?php
class b2c_tasks_sosynchronization extends base_task_abstract implements base_interface_task{
  public function exec($params=null){

    // //add by lkb 2017-06-20 U8订单是否自动审批
    // $ismonthpayapprove=app::get('b2c')->getConf('system.member.monthpayapprove');
    // //add end


    //定义未同步sql
    //edit by peter 2017-06-05
    /*过滤条件说明:订单行数量:大于0,未同步,订单状态:活动订单,是否失效:否*/
    $sqlorder='select  a.order_id,is_synchronization from sdb_b2c_orders a left join sdb_b2c_order_items b on a.order_id = b.order_id where b.nums>0 and  is_synchronization<>"true" and (a.`status`="active" or a.`status`="finish") and a.disabled="false" group by a.order_id;';
    $db =kernel::database();
    $orderdata  = $db->select($sqlorder);
    if(!empty($orderdata))
    {
      foreach ($orderdata as $ordervalue)
      {
        //edit by peter 2017-06-05 修改:支付状态值
        $sql1=" select b.order_id 单号
        ,b.createtime 下单时间,c.u8code u8客户编码
        ,b.ship_addr 备注
        ,case when c.monthpay = '1' then '是' else '否' end 是否月结客户
        ,case b.pay_status when '0' then '未支付' when '1' then '已支付' when '2' then '已付款至到担保方' when '3' then '部分付款' when '4' then '部分退款' when '5' then '全额退款' when '6' then '退款申请中' end 支付状态
	,case when (c.monthpay='1' or b.pay_status in ('1','2','3')) then '是' else '否'  end as sender
        ,d.local_name 办事处,'电商订单' 备注1,e.bn 编码,a.name 名称,a.price 单价,a.nums 数量,a.amount 总额
	,a.item_id 明细ID,(a.amount-ifnull(f.pmt_amount,0)) as realamount,ifnull(g.name,'') as pmtname,ifnull(f.pmt_amount,0) as pmt_amount,b.monthpayapprove_status as 月结客户审核状态
  ,b.ship_name 收货人,b.ship_mobile 收货电话,b.memo  订单附言
        from sdb_b2c_order_items a
        inner join sdb_b2c_orders b on a.order_id = b.order_id
        left JOIN sdb_b2c_members c on b.member_id = c.member_id
        left join sdb_ectools_office d on c.office_id = d.office_id
        LEFT JOIN sdb_b2c_products e on a.product_id = e.product_id
	left join sdb_b2c_order_pmt f on a.order_id=f.order_id and a.product_id=f.product_id
	left join sdb_b2c_sales_rule_order g on f.pmt_id=g.rule_id and g.c_template='proqgoods_conditions_goods_goodsofquantity2'
        where a.nums>0 and a.order_id= ".$ordervalue['order_id'] ;
        $db1 =kernel::database();
        $data  = $db1->select($sql1);
        $json='';
	//add by peter 2017-06-12 单头合并首批打折信息
       	foreach($data as $value){
		if (strlen($pmtname)!=0 && strlen($value['pmtname'])!=0){
			$pmtname.=',';
		}
			$pmtname.=$value['pmtname'];
	}	
        foreach($data as $value) {

          //add by lkb 2017-06-22 月结客户未审核订单不能传到u8
          if($value['是否月结客户']=='是'&&$value['月结客户审核状态']=='0')
          {
              continue;
          }
            if(strlen($json)>0) {$json.=',';}
            $json .= '{"Office":"'.$value['办事处'].'"' ;
            $json .= ',"Businessdate":"'.date('Y-m-d', $value['下单时间']) .'"';
            $json .= ',"OrderBy":"'.$value['u8客户编码'].'"';
            $json .= ',"Memo":"'. $value['备注'].'-'. $value['收货人'].'-'. $value['收货电话'].'-'.$value['订单附言'].'"';
            $json .= ',"B2BDocNo":"'.$value['单号'].'"';
            $json .= ',"PaymentStatus":"'.$value['支付状态'] .'"';
            $json .= ',"MonCutomer":"'.$value['是否月结客户'].'"' ;

            //add by lkb 2017-06-20 U8订单符合条件的全部审批
            $ismonthpayapprove='1';
            $json .= ',"ismonthpayapprove":"'.$ismonthpayapprove.'"' ;
            //add end

            //add by peter 2017-06-06 是否能发货
	    $json .= ',"Sender":"'.$value['sender'].'"';
	    //add by peter 2017-06-12 首批打折信息
	    $json .= ',"Pmtname":"'.$pmtname.'"';
            $json .= ',"ItemCode":"'.$value['编码'].'"';
            $json .= ',"Qty":'.$value['数量'];
	    //edit by peter 2017-06-12 传入价税合计
            //$json .= ',"Price":'.$value['单价'];
	    $json .= ',"Amount":'.$value['realamount'];
            $json .= ',"B2BLineNo":"'.$value['明细ID'].'"}' ;
        }
        $json = '{ "orders":[ '.$json;
        $json .= " ]}";
        //测试请求地址 web.kingzest.com 二级域名，不能用IP访问
        //$wsdl ="http://web.kingzest.com/webservices/WebService.asmx?wsdl";
	$wsdl=U8_SOWSDL;
        try
        {
          $client = new SoapClient($wsdl);
        } catch (Exception $e) {   
	  $this->writeLog($e->getMessage(),'实例化请求地址时出错,请检查');
          return;
        }

        try
        { 
          $output = $client->AddInSt($json);
        }catch (Exception $e) { 
	  $this->writeLog($e->getMessage(),'订单同步异常');
        }
        $response_datas=json_decode($output,true);

        //U8 返回值格式实例[{"no":"12345678","statue":"fail","result":"12345678客户不能为空或者不存在订单[]客户不能为空."}]
        if(is_array($response_datas) )
        {
          if($response_datas[0]['statue'] == 'ok')
          {
            //订单同步成功反写数据
            $mdl_order = app::get('b2c')->model('orders');
            $ordersql='update sdb_b2c_orders set is_synchronization="true",u8docno="'.$response_datas[0]['result'].'" where order_id ='.$ordervalue['order_id'] ;
            $mdl_order->db->exec($ordersql);

          }else{
	    $this->writeLog($response_datas[0]['result'],'订单同步异常',$response_datas[0]['no']);
          }
        }

      }//循环未同步的订单
    }//if empty 是否查到有未同步的订单
  }//function

//add by peter 2017-06-06写日志方法
private function writeLog($failureReason,$memo='',$docno=0){
$model1 = app::get('b2c')->model('synerrorlog');
            $data1 = array(
              'CreateTime'=>time(),
              'CrontabId'=>'b2c_tasks_sosynchronization',
              'DocNo'=>$docno ,
              'Issyn'=>'false' ,
              'FailureReason'=> $failureReason ,
              'Memo' =>$memo,
              );
$model1->insert($data1);
}

}//class
